package com.fastPlat.scheduled;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;

@Component
public class ScheduledMessageConsumer {
	
	@Autowired
	private DefaultMQPushConsumer shopConsumer;
	
	@PostConstruct
	public void startConsumer(){
		try {
			shopConsumer.setConsumeMessageBatchMaxSize(10);//每次拉取10条
			shopConsumer.setMessageModel(MessageModel.BROADCASTING);// 广播消费  

	        // 注册监听器
			shopConsumer.registerMessageListener(new MessageListenerConcurrently() {
	            @Override
	            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
	                for (MessageExt message : messages) {
	                    // Print approximate delay time period
	                    System.out.println("Receive message[msgId=" + message.getMsgId() + "] "
	                            + (System.currentTimeMillis() - message.getStoreTimestamp()) + "ms later");
	                }
	                //System.out.println(ConsumeConcurrentlyStatus.CONSUME_SUCCESS);
	                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
	            }
	        });
	        // Launch consumer
			shopConsumer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@PreDestroy
	public void destroy() {
		shopConsumer.shutdown();
	}
}
